home *** CD-ROM | disk | FTP | other *** search
- Path: newshost.cyberramp.net!news
- From: sinan@cyberramp.net (John L. Noland)
- Newsgroups: comp.lang.c
- Subject: Re: Recursion
- Date: 5 Apr 1996 02:08:48 GMT
- Organization: CyberRamp
- Message-ID: <4k1vbg$6gu@newshost.cyberramp.net>
- References: <31624BC2.70D2@sooner.net>
- NNTP-Posting-Host: ramp1-7.cyberramp.net
- X-Newsreader: WinVN 0.99.5
-
- n article <31624BC2.70D2@sooner.net>, edwbush@sooner.net says...
- >
- >I am trying to construct a C function that will recursively convert
- >a string such as "1234" into it's integer equivelant (1234).
- >
- >Here is what I know:
- >1)if you subtract the character "0" from any of the other digits "1".."9"
- > you will get the integer value of that characer.
- > Example: "1" - "0" is equal to 1
- > "2" - "0" is equal to 2
- > .
- > .
- > .
- > "9" - "0" is equal to 9
- >2)the function should be called with a character pointer:
- > Such as: convert("1234");
- > making the prototype look something like:
- > int convert(char *p);
- >
- >Does anyone have an idea? This is sorta stumping me. I am aware of
- >atoi, but I am wanting to write a recursive function that does that --
- >for the fun of it. It's sort of a little puzzle to help me learn
- >recursion. Any ideas?
- >
- >Thanx in Advance!
- >
-
- void convert (char *buf, int result);
-
- int main (void) {
-
- char str[] = "1234";
- int result = 0;
-
- convert(str, result);
- return 0;
-
- }
-
- void convert (char *buf, int result) {
-
- int check_array[100]; /* Good for strings of numbers up to 100 digits long! */
- int i = 0, j = 0;
-
- if (*buf = '\0') return;
- j = i; /*Save i */
- for (i = 0; i < 100; i++)
- check_array[i] = 0; /*Initialize our array */
- i = j; /*Restore i */
- check_array[i] = (int)(*buf - '0'); /*Convert ASCII to integer and save */
- i += 1; /*increment i */
- j = i; /*Save i for later*/
- for (i = 0; i < 100; i++)
- result += check_array[i]; /*tally up the numbers */
- i = j; /*restore i to previous */
- buf += i; /*advance our pointer */
- convert(buf, result);
- if (*buf = '\0') return;
- }
-
- This could probably be made a little more efficient, but I think this'll work
- for you. Didn't test it though!
-
- Helping with homework is good for the soul!
-
- -John
-
-
-